package com.ccx.coachsite.downloadmgr;


import java.io.File;
import java.lang.Thread.UncaughtExceptionHandler;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.NotificationManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.ccx.coachsite.R;
import com.ccx.coachsite.util.FileUtil;
import com.ccx.coachsite.util.GraphicUtils;
import com.ccx.coachsite.util.SUtil;
import com.ccx.coachsite.util.U;
import com.ccx.coachsite.util.Utilities;

/**
 * 显示已下载记录的界面
 *
 */
public class DownloadedActivity extends Activity implements UncaughtExceptionHandler,OnItemClickListener{

	/*------------------------------控件区------------------------------------*/
	private ListView lv_list;
	private LinearLayout ll_loading; //正在加载。。。
	private LinearLayout ll_no_data; //未找数据显示的提示
	private Button btn_nodata_reflash; //未找到数据显示的刷按钮
	private TextView tv_delete_all;//删除全部的按钮
	private TextView tv_downloading;
	
	/*------------------------------其他变量------------------------------------*/
	private List<DownloadItem> mItems;
	private NoInstallComparator mComparator=new NoInstallComparator();//排序器
	private UninstallReceiver mUninstallReceiver=new UninstallReceiver(); //应用安装与卸载监听
	private DownloadStatusReceiver mDownloadStatusReceiver;//下载状态变化监听器
	private NotificationManager mNotifyManager;
	private PackageManager pm;
	
	/*------------------------------公共变量------------------------------------*/
	private Context mContext;
	private DownloadAdapter mAdapter;
	private Bitmap mDefaultBitmap;
	
	private final int EVENT_COMMON=20000;
	private final int EVENT_FRIST_LOADING=20001;
	
	private Runnable mRunLoadIcon; //加载图标线程
	private Runnable mRunLoadInfo; //加载列表文字信息线程
	private Handler mHandler;
	private Handler mEventHandler=new Handler(){

		@Override
		public void handleMessage(Message msg) {
			ll_loading.setVisibility(View.GONE);
			switch(msg.what)
			{
			//第一次加载结束
			case EVENT_FRIST_LOADING:
				if(mItems!=null&&mItems.size()>0)
				{
					mAdapter.notifyDataSetChanged();
					ll_no_data.setVisibility(View.GONE);
					String dledPrefix=getString(R.string.common_has_download);//"已下载"
					StringBuffer sb=new StringBuffer();
					sb.append(dledPrefix).append(":").append(mItems.size());
					tv_downloading.setText(sb.toString());
				}else{//当前没有已下载的资源
					TextView tv_nodata_main=(TextView) ll_no_data.findViewById(R.id.tv_nodata_main);
					tv_nodata_main.setText(getText(R.string.common_no_downloaded_data));
					tv_nodata_main.setCompoundDrawablesWithIntrinsicBounds(null, null, null, null);
					ll_no_data.setVisibility(View.VISIBLE);
				}
					
				break;
			case EVENT_COMMON:
				mAdapter.notifyDataSetChanged();
				break;
			}
			
		}
		
	};
	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.download_mgr_downloading);
		mContext=this;
		Drawable defDrawable=getResources().getDrawable(R.drawable.icon);
		mDefaultBitmap=((BitmapDrawable)defDrawable).getBitmap();
		Thread.setDefaultUncaughtExceptionHandler(this);
		
		mItems=new ArrayList<DownloadItem>();
		mHandler=new Handler();
		mNotifyManager=(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        pm=getPackageManager();
		
		//监听安装与卸载广播
        IntentFilter filter = new IntentFilter(Intent.ACTION_PACKAGE_REMOVED);
        filter.addAction(Intent.ACTION_PACKAGE_ADDED);
        filter.addDataScheme("package");
        this.registerReceiver(mUninstallReceiver, filter);
		
        //注册下载状态变化监听
		IntentFilter dlStatusFilter=new IntentFilter();
		dlStatusFilter.addAction(DownloadService.DOWNLOAD_STATUS_CHANGE_RECEIVER);
		mDownloadStatusReceiver=new DownloadStatusReceiver();
		registerReceiver(mDownloadStatusReceiver, dlStatusFilter);
		
		initView();
	}
	
	/**
	 * 对外广播下载状态
	 * @param item
	 */
	private void broadcastStatus(DownloadItem item)
	{
		Intent intent=new Intent(DownloadService.DOWNLOAD_STATUS_CHANGE_RECEIVER);
		intent.putExtra(DownloadItem.EXTRA_ME, item);
		mContext.sendBroadcast(intent);
	}
	
	/**
	 * 初始化视图
	 */
	private void initView()
	{
		lv_list=(ListView) findViewById(R.id.lv_list);
		ll_loading=(LinearLayout) findViewById(R.id.ll_loading);
		tv_downloading=(TextView)findViewById(R.id.tv_downloading);
		ll_no_data=(LinearLayout)findViewById(R.id.ll_no_data);
		tv_delete_all=(TextView)findViewById(R.id.tv_delete_all);
		tv_delete_all.setVisibility(View.VISIBLE);
		
		btn_nodata_reflash=(Button)ll_no_data.findViewById(R.id.btn_nodata_reflash);
		btn_nodata_reflash.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				loadDownloadedData();
			}
		});
		
		//删除全部
		tv_delete_all.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				//确认全部删除否
				String tipMsg=getString(R.string.common_button_confirm)+getString(R.string.common_delete_all)+"?";
				new AlertDialog.Builder(getParent()).setTitle(R.string.common_tip)
					.setMessage(tipMsg)
					.setPositiveButton(R.string.common_button_confirm, new DialogInterface.OnClickListener() {
						
						@Override
						public void onClick(DialogInterface dialog, int which) {
							new Thread(new Runnable() {
								
								@Override
								public void run() {
									
									DownloadDAO.removeAll();
									//逐一删除APK文件
									for(DownloadItem item:mItems)
									{
										File file=new File(item.getFilePath());
										if(file.exists())
										{
											try {
												file.delete();
											} catch (Exception e) {
												
											}
										}
										item.setStatus(DownloadItem.STATUS_NONE);
										broadcastStatus(item);
										mNotifyManager.cancel(Integer.parseInt(item.getSid()));
									}
									
									mItems.clear();
									sendMessage(EVENT_FRIST_LOADING);
								}
							}).start();
						}
					}).setNegativeButton(R.string.common_button_cancell, new DialogInterface.OnClickListener() {
						
						@Override
						public void onClick(DialogInterface dialog, int which) {
							dialog.dismiss();
						}
					}).create().show();
				
			}
		});

		lv_list.setOnItemClickListener(this);
		loadDownloadedData();
	}
	
	/**
	 * 加载已下载的数据
	 */
	private void loadDownloadedData()
	{
		ll_no_data.setVisibility(View.GONE);
		ll_loading.setVisibility(View.VISIBLE);
		mItems.clear();
		mRunLoadInfo=new Runnable() {
			
			@Override
			public void run() {
				try {
					
					/* ------------------已下载的---------------------------- */
					List<DownloadItem> localItems=DownloadDAO.getHistoryList(mContext);
					if(localItems!=null){
						mItems.addAll(localItems);
						sortItems();//排序
					}
					sendMessage(EVENT_FRIST_LOADING);
					//加载图标
					loadIcon();
				} catch (Exception e) {
					e.printStackTrace();
				}
				
			}
		};
		
		mHandler.post(mRunLoadInfo);
		mAdapter=new DownloadAdapter(mContext,mItems);
		lv_list.setAdapter(mAdapter);
	
	}
	
	/**
	 * 加载列表 的图标
	 */
	private void loadIcon() 
	{
		mRunLoadIcon=new Runnable() {
			
			public void run() {
				for(int i=0;i<mItems.size();i++)
				{
					DownloadItem item=mItems.get(i);
					if(item==null)
						continue;
					String iconPath=item.getIconPath();
					Bitmap tmpBmp=null;
					if(FileUtil.isFileExits(iconPath))//存在图标缓存文件，则加载它
						tmpBmp=GraphicUtils.getImageFile(item.getIconPath(), getWindowManager().getDefaultDisplay());
					else 
					{
						//已安装的情况，从安装的应用中获取图标
						Drawable d = null;
						try {
							d = pm.getApplicationIcon(item.getPkgName());
						} catch (NameNotFoundException e) {
							d=null;
						}
						
						if(d==null)
							tmpBmp=mDefaultBitmap;
						else
							tmpBmp=Utilities.createIconBitmap(d, mContext);
					}
					
					item.setIcon(tmpBmp);
					
					if((i+1)%10==0||i==mItems.size()-1)
					{
						sendMessage(EVENT_COMMON);
					}
				}//end for
				
			}
		};
				
		mHandler.post(mRunLoadIcon);
					
	}

	/**
	 * 显示操作对话框
	 */
	private void showOperDialog(int pos)
	{
		final DownloadItem item=mItems.get(pos);
		String[] strItems=new String[2];
		final int status=item.getStatus();
		if(status==DownloadItem.STATUS_DOWNLOADED)
			strItems[0]=getString(R.string.common_button_install);//安装
		else
			strItems[0]=getString(R.string.common_button_uninstall);//卸载
		strItems[1]=getString(R.string.common_button_del);//删除
		new AlertDialog.Builder(getParent()).setTitle(item.getTitle()).setIcon(new BitmapDrawable(item.getIcon()))
						.setItems(strItems, new DialogInterface.OnClickListener() {
			
					@Override
					public void onClick(DialogInterface dialog, int which) {
						switch(which)
						{
						
						case 0:
							if(status==DownloadItem.STATUS_DOWNLOADED)//安装APK
								U.installApplication(mContext,item);
							else
								U.uninstallApp(mContext, item);//卸载
							break;
						//删除APK
						case 1:
							confirmDelete(item);
							break;
						}
					}
				}).create().show();
	}


	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
		DownloadItem item=mItems.get(position);
		int status=item.getStatus();
		if(status==DownloadItem.STATUS_DOWNLOADED||status==DownloadItem.STATUS_INSTALLED)
			showOperDialog(position);
	}
	
	
	/**
	 * 删除历史记录和APK文件
	 * @param item
	 */
	private void deleteHistory(DownloadItem item)
	{
		try {
			DownloadDAO.removeHistory(item);
			String apkPath=item.getFilePath();
			//再删除 APK文件
			File file=new File(apkPath);
			if(file.exists())
				file.delete();
		} catch (Exception e) {
		}
		
		
	}
	
	
	/**
	 * 确认删除
	 */
	private void confirmDelete(DownloadItem item)
	{
		final DownloadItem fItem=item;
		String tipMsg=getString(R.string.common_downloaded_delete_confirm);
		new AlertDialog.Builder(getParent()).setTitle(R.string.common_tip)
			.setMessage(tipMsg.replace("{0}", fItem.getTitle()))
			.setPositiveButton(R.string.common_button_confirm, new DialogInterface.OnClickListener() {
				
				@Override
				public void onClick(DialogInterface dialog, int which) {
					deleteHistory(fItem);
					fItem.setStatus(DownloadService.getDownloadStatus(mContext, fItem));
					broadcastStatus(fItem);
					mItems.remove(fItem);
					sendMessage(EVENT_FRIST_LOADING);
					//删除完将消息栏中该提示消除，当然是提示栏有该记录的提醒，没有自然也不用消除了
        			mNotifyManager.cancel(Integer.parseInt(fItem.getSid()));
					
				}
			}).setNegativeButton(R.string.common_button_cancell, new DialogInterface.OnClickListener() {
				
				@Override
				public void onClick(DialogInterface dialog, int which) {
					dialog.dismiss();
				}
			}).create().show();
	}
	
	
	/**
	 * 对集合进行排序
	 */
	private void sortItems()
	{
		Collections.sort(mItems,mComparator);
	}
	
	/**
	 * 根据是否安装的排序器，未安装的排在前面
	 *
	 */
	private class NoInstallComparator implements Comparator<DownloadItem>
	{

		@Override
		public int compare(DownloadItem d1,DownloadItem d2) {
			int status1=d1.getStatus();
			int status2=d2.getStatus();
			String time1=d1.getDownloadTime()==null?"0":d1.getDownloadTime();
			String time2=d2.getDownloadTime()==null?"0":d2.getDownloadTime();
			long Ltime1=Long.parseLong(time1.replaceAll("\\D", ""));
			long Ltime2=Long.parseLong(time2.replaceAll("\\D", ""));
			
			/*-----------------正在下载的------------------*/
			if(status1==DownloadItem.STATUS_DOWNLOADING&&status2==DownloadItem.STATUS_DOWNLOADING)
				return 0;
			if(status1==DownloadItem.STATUS_DOWNLOADING)
				return -1;
			if(status2==DownloadItem.STATUS_DOWNLOADING)
				return 1;
			
			/*-----------------下载失败------------------*/
			if(status1==DownloadItem.STATUS_DOWNLOAD_FAILED&&status1==DownloadItem.STATUS_DOWNLOAD_FAILED)
				return 0;
			if(status1==DownloadItem.STATUS_DOWNLOAD_FAILED)
				return -1;
			if(status2==DownloadItem.STATUS_DOWNLOAD_FAILED)
				return 1;
			
			
			
			/*-----------------已下载，未安装------------------*/
			
			if(status1==DownloadItem.STATUS_DOWNLOADED&&status2==DownloadItem.STATUS_DOWNLOADED)
				return -1*(int)(Ltime1-Ltime2);
			
			if(status1==DownloadItem.STATUS_DOWNLOADED)
				return -1;
			if(status2==DownloadItem.STATUS_DOWNLOADED)
				return 1;
			
			/*-----------------已安装------------------*/
			if(status1==DownloadItem.STATUS_INSTALLED&&status2==DownloadItem.STATUS_INSTALLED)
				return -1*(int)(Ltime1-Ltime2);
			if(status1==DownloadItem.STATUS_INSTALLED)
				return 1;
			if(status2==DownloadItem.STATUS_INSTALLED)
				return -1;
			
			return 0;
		}
		
	}
	
    
    @Override
	protected void onResume() {
		super.onResume();
	}
    

	@Override
	protected void onPause() {
		super.onPause();
	}
	
	/**
     * 清除缓存
     */
    private void clearCache()
    {
    	try {
    		
    		//注销下载状态监听
    		unregisterReceiver(mDownloadStatusReceiver);
    		//注销应用安装与卸载监听
    		unregisterReceiver(mUninstallReceiver);
    		mHandler.removeCallbacks(mRunLoadIcon);
        	mHandler.removeCallbacks(mRunLoadInfo);
        	for(DownloadItem item:mItems)
        	{
        		if(item!=null)
        		{
        			Bitmap icon=item.getIcon();
        			if(icon!=null&&!icon.isRecycled())
        				icon.recycle();
        		}
        	}
        	if(mItems!=null){
        		mItems.clear();
        		mItems=null;
        	}
		} catch (Exception e) {
			//e.printStackTrace();
		}
    	
    }
	
	@Override
	protected void onDestroy() {
		clearCache();
		super.onDestroy();
	}
		
	@Override
	public void uncaughtException(Thread thread, Throwable ex) {
		ex.printStackTrace();
		finish();
	}
	
	private void sendMessage(int what)
	{
		Message msg=new Message();
		msg.what=what;
		mEventHandler.sendMessage(msg);
	}
	
	
	
	/*-------------------------------内部类区------------------------------------------*/
	/**
     * 安装与卸载监听
     *
     */
    private class UninstallReceiver extends BroadcastReceiver {
    	@Override
    	public void onReceive(Context context, Intent intent) {
    		String action=intent.getAction();
    		String dataStr=intent.getDataString();
    		String insPkg=dataStr.substring(8);
    		int status=0;
    		if(action.equals(Intent.ACTION_PACKAGE_ADDED))//安装
    			status=DownloadItem.STATUS_INSTALLED;
    		else if(action.equals(Intent.ACTION_PACKAGE_REMOVED))//卸载
    			status=DownloadItem.STATUS_DOWNLOADED;
    			
    		for(DownloadItem item:mItems)
    		{
    			if(item.getPkgName().equals(insPkg))
    			{
    				item.setStatus(status);
    				sortItems();
        			sendMessage(EVENT_FRIST_LOADING);
        			//安装完将消息栏中该提示消除，当然是提示栏有该记录的提醒，没有自然也不用消除了
        			mNotifyManager.cancel(Integer.parseInt(item.getSid()));
        			break;
    			}
    		}
    		
    	}
	}//UninstallReceiver
    
    /**
     * 下载状态改变监听器
     */
    private class DownloadStatusReceiver extends BroadcastReceiver{

		@Override
		public void onReceive(Context context, Intent intent) {
			DownloadItem dItem=(DownloadItem) intent.getSerializableExtra(DownloadItem.EXTRA_ME);
			if(dItem!=null && dItem.getStatus()==DownloadItem.STATUS_DOWNLOADED)
			{
				//有任务下载完成，将新下载的数据添加到列表中
				//从文件中获取图标图片
				Bitmap icon=BitmapFactory.decodeFile(dItem.getIconPath());
				
				//从安装的应用中获取
				if(icon==null)
				{
					try {
						Drawable d=pm.getApplicationIcon(dItem.getPkgName());
						icon=((BitmapDrawable)d).getBitmap();
					} catch (NameNotFoundException e) {
						icon=null;
					}
					
				}
				//默认图标
				icon=icon==null?mDefaultBitmap:icon;
				dItem.setIcon(icon);
				mItems.add(0, dItem);
				sendMessage(EVENT_FRIST_LOADING);
			}
		}
		
    	
    }//end DownloadStatusReceiver
    
    /**
     * 列表的Adapter
     */
    private class DownloadAdapter extends BaseAdapter{
    	
    	private Context mCtx;
    	private List<DownloadItem> mItemList;
    	private LayoutInflater mInflater;
    	public DownloadAdapter(Context ctx, List<DownloadItem> items) {
    		mItemList=items;
    		mCtx=ctx;
    		mInflater=(LayoutInflater) mCtx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    	}
    	
    	@Override
		public int getCount() {
			return mItemList.size();
		}
		@Override
		public Object getItem(int position) {
			return mItemList.get(position);
		}
		@Override
		public long getItemId(int position) {
			return position;
		}
		
    	@Override
    	public View getView(int position, View convertView, ViewGroup parent){
    		DownloadItem item=mItemList.get(position);
    		Holder holder=null;
    		View view=null;
    		if(convertView==null)
    		{
    			view=mInflater.inflate(R.layout.download_list_item, null);
    			holder=new Holder();
    			holder.im_imageInfo=(ImageView) view.findViewById(R.id.im_imageInfo);
    			holder.tv_title=(TextView) view.findViewById(R.id.tv_title);
    			holder.tv_version=(TextView) view.findViewById(R.id.tv_version);
    			holder.tv_size=(TextView) view.findViewById(R.id.tv_size);
    			holder.tv_time=(TextView) view.findViewById(R.id.tv_time);
    			holder.tv_delete=(TextView)view.findViewById(R.id.tv_delete);
    			holder.tv_oper=(TextView) view.findViewById(R.id.tv_oper);
    			holder.ll_progress=(LinearLayout) view.findViewById(R.id.ll_progress);
    			view.setTag(holder);
    			
    		}else
    			view=convertView;
    		
    		String versionPrefix=mContext.getText(R.string.common_version)+":";
    		String sizePrefix=mContext.getText(R.string.common_size)+":";
    		String timePrefix=mContext.getText(R.string.common_download_time)+":";
    		
    		holder=(Holder) view.getTag();
    		holder.im_imageInfo.setImageBitmap(item.getIcon());
    		holder.tv_title.setText(item.getTitle());
    		holder.tv_version.setText(versionPrefix+item.getAvailVersion());
    		
    		String size=SUtil.getComputerSize(item.getFileBytes(), 2);
    		holder.tv_size.setText(sizePrefix+size);
    		holder.tv_time.setTextColor(Color.LTGRAY);
    		
    		ClickListener clickListener=new ClickListener(position);
    		holder.tv_delete.setOnClickListener(clickListener);
    		holder.tv_oper.setOnClickListener(clickListener);
    		
    		if(!SUtil.isZhLanguage())//非中文界面下，把字号改小
    		{
    			holder.tv_delete.setTextSize(11);
    			holder.tv_oper.setTextSize(11);
    		}
    		
    		switch(item.getStatus())
    		{
    		//已下载
    		case DownloadItem.STATUS_DOWNLOADED:
    			holder.tv_time.setVisibility(View.VISIBLE);
    			holder.tv_time.setText(timePrefix+item.getDownloadTime());
    			holder.ll_progress.setVisibility(View.GONE);
    			holder.tv_oper.setText(mContext.getString(R.string.common_button_install));
    			break;
    		//已安装
    		case DownloadItem.STATUS_INSTALLED:
    			holder.tv_time.setVisibility(View.VISIBLE);
    			holder.tv_time.setText(timePrefix+item.getDownloadTime());
    			holder.ll_progress.setVisibility(View.GONE);
    			holder.tv_oper.setText(mContext.getString(R.string.common_button_uninstall));
    			break;
    		}
    		
    		return view;
    	}
    	
    	private class Holder{
    		public ImageView im_imageInfo;
    		public TextView tv_title;
    		public TextView tv_version;
    		public TextView tv_size;
    		public LinearLayout ll_progress;
    		public TextView tv_time;
    		public TextView tv_delete;
    		public TextView tv_oper;
    	}
    	
    	private class ClickListener implements android.view.View.OnClickListener{

    		private DownloadItem mAdapterItem;
    		public ClickListener(int pos){
    			mAdapterItem=mItemList.get(pos);
    		}
    		
    		@Override
    		public void onClick(View v) {
    			if(v.getId()==R.id.tv_oper)
    			{
    				switch(mAdapterItem.getStatus())
        			{
        			//已下载，则安装
        			case DownloadItem.STATUS_DOWNLOADED:
        				U.installApplication(mContext, mAdapterItem);
        				break;
        			//已安装，则卸载
        			case DownloadItem.STATUS_INSTALLED:
        				U.uninstallApp(mContext, mAdapterItem);
        				break;
        				
        			}//end switch
    				
    			}else if(v.getId()==R.id.tv_delete){ //删除APK
    				//确认删除否
    				confirmDelete(mAdapterItem);
    				
    			} //end if
    			
    		}// end onClick
    		
    	}// end ClickListener

		
    	
    }// end InstallAdapter

}
